//
//  ACLogUpload.swift
//  ACFrameworkSwift
//
//  Created by fisherman on 2021/9/3.
//

import Foundation

public struct ACLogUpload {
    
    /// 获取当天的日期字符串，格式为："yyyy-MM-dd"
    public static var todayDate: String {
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd"
        return format.string(from: Date())
    }
    
    /// 上传指定日期的日志
    /// - Parameters:
    ///   - urlStr: 接收日志的服务器完整 url
    ///   - date: 日期，不传默认为今天，格式： "2021-09-03"
    ///   - completion: 结果回调 （data, response, error）
    public static func uploadLog(urlStr: String, date: String = todayDate, completion: ((Data?, URLResponse?, String?) -> Void)?) {

        let logFile = "\(ACLog.default.logPath)/\(ACLog.default.defaultNamePrefix)_\(date).xlog"
        guard FileManager.default.fileExists(atPath: logFile) == true else {
            DispatchQueue.main.async {
                completion?(nil, nil, "日志文件不存在")
            }
            return
        }
        
        guard let url = URL(string: urlStr) else {
            DispatchQueue.main.async {
                completion?(nil, nil, "url 错误")
            }
            return
        }
        
        var req = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60)
        req.httpMethod = "POST"
        req.setValue("binary/octet-stream", forHTTPHeaderField: "Content-Type")
        if let bundleIdentifiler = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as? String {
            req.setValue(bundleIdentifiler, forHTTPHeaderField: "bundleId")
        }
        if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
            req.setValue(version, forHTTPHeaderField: "appVersion")
        }
        if let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String {
            req.setValue(build, forHTTPHeaderField: "bundleVersion")
        }
        
        let fileURL = URL(fileURLWithPath: logFile)
        let task = URLSession.shared.uploadTask(with: req, fromFile: fileURL) { data, response, error in
            DispatchQueue.main.async {
                completion?(data, response, error?.localizedDescription)
            }
        }
        task.resume()
    }
    
}
